package com.cr.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	private String driver	= "";	
	private String url		= "";
	private String user		= "";	
	private String password	= "";	
	
	private Connection conn=null;
	
	public DBUtil()
	{
		init();
		try
		{
			Class.forName(this.driver);
		}
		catch(ClassNotFoundException ex)
		{
			ex.printStackTrace();
		}
		
		try {
			conn=DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 
	 */
	private void init()
	{
		ConfigManager instance=ConfigManager.getInstance();
		if(instance!=null)
		{
			this.driver=instance.getValue("jdbc.driver");
			this.url=instance.getValue("jdbc.url");
			this.user=instance.getValue("jdbc.user");
			this.password=instance.getValue("jdbc.password");
		}
	}
	
	public ResultSet query(String sql)
	{
		ResultSet rs=null;
		Statement stm=null;
		try {
			stm=conn.createStatement();
			rs = stm.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public ResultSet preQuery(String sql,Object[] args)
	{
		ResultSet rs=null;
		
		try {
			PreparedStatement pst=conn.prepareStatement(sql);
			if(args!=null && args.length>0)
			{
				for(int i=0;i<args.length;i++)
				{
					pst.setObject(i+1, args[i]);
				}
			}
			rs=pst.executeQuery();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public int preExecute(String sql,Object[] args)
	{
		try {
			PreparedStatement pst=conn.prepareStatement(sql);
			if(args!=null && args.length>0)
			{
				for(int i=0;i<args.length;i++)
				{
					pst.setObject(i+1, args[i]);
				}
			}
			return pst.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}
	
	public int execute(String sql)
	{
		Statement stm=null;
		try {
			stm=conn.createStatement();
			return stm.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return -1;
	}
	
	public void Close()
	{
		try
		{
		if(conn!=null && !conn.isClosed())
		{
			conn.close();
		}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
	}
}
